import axios from 'axios'
import router from '../router'
import { useMainStore } from '../../stores/index'

const request = axios.create({
  baseURL: 'http://localhost:3001/api',
  timeout: 5000,
})

// 请求拦截器，自动加 token
request.interceptors.request.use(
  (config) => {
    const store = useMainStore()
    if (store.token) {
      config.headers.Authorization = `Bearer ${store.token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器，401 跳转登录
request.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response && error.response.status === 401) {
      const store = useMainStore()
      store.setToken('')
      store.setUser(null)
      router.replace('/register')
    }
    return Promise.reject(error)
  }
)

export default request
